from flask import Blueprint, request, jsonify
from src.models.models import db, PracticeLog, Mistake, Word
from datetime import datetime

practice_bp = Blueprint('practice', __name__)

@practice_bp.route('/record-practice', methods=['POST'])
def record_practice():
    """记录练习日志"""
    try:
        data = request.get_json()
        user_id = data.get('user_id')
        word_id = data.get('word_id')
        action = data.get('action')  # view/tts/record/score
        score = data.get('score')
        correct = data.get('correct')
        
        if not all([user_id, word_id, action]):
            return jsonify({'success': False, 'error': 'Missing required fields'}), 400
        
        # 创建练习日志
        log = PracticeLog(
            user_id=user_id,
            word_id=word_id,
            action=action,
            score=score,
            correct=correct
        )
        db.session.add(log)
        
        # 如果答错了，更新错词本
        if correct is False:
            mistake = Mistake.query.filter_by(user_id=user_id, word_id=word_id).first()
            if mistake:
                mistake.count += 1
                mistake.last_timestamp = datetime.utcnow()
                mistake.mastery_level = max(0, mistake.mastery_level - 10)
            else:
                mistake = Mistake(
                    user_id=user_id,
                    word_id=word_id,
                    count=1,
                    mastery_level=20
                )
                db.session.add(mistake)
        elif correct is True:
            # 答对了，提升掌握度
            mistake = Mistake.query.filter_by(user_id=user_id, word_id=word_id).first()
            if mistake:
                mistake.mastery_level = min(100, mistake.mastery_level + 10)
                if mistake.mastery_level >= 80:
                    # 掌握度高，可以考虑从错词本移除
                    pass
        
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': 'Practice recorded successfully'
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'error': str(e)}), 500

@practice_bp.route('/review-pool', methods=['GET'])
def get_review_pool():
    """获取复习池（错词本）"""
    try:
        user_id = request.args.get('user_id', type=int)
        if not user_id:
            return jsonify({'success': False, 'error': 'user_id is required'}), 400
        
        # 获取掌握度低于60的错词
        mistakes = db.session.query(Mistake, Word).join(Word).filter(
            Mistake.user_id == user_id,
            Mistake.mastery_level < 60
        ).order_by(Mistake.last_timestamp.desc()).all()
        
        result = []
        for mistake, word in mistakes:
            word_dict = word.to_dict()
            word_dict['mistake_info'] = mistake.to_dict()
            result.append(word_dict)
        
        return jsonify({
            'success': True,
            'data': result
        })
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@practice_bp.route('/speech-score', methods=['POST'])
def speech_score():
    """语音评分接口（模拟）"""
    try:
        data = request.get_json()
        text = data.get('text')
        audio_data = data.get('audio_data')  # base64 encoded audio
        
        # 模拟评分逻辑
        import random
        score = random.randint(60, 95)
        accuracy = 'Good' if score >= 80 else 'Fair' if score >= 70 else 'Poor'
        stress = random.choice(['Good', 'Fair', 'Poor'])
        linking = random.choice(['Good', 'Fair', 'Poor'])
        
        return jsonify({
            'success': True,
            'data': {
                'overall_score': score,
                'accuracy': accuracy,
                'stress': stress,
                'linking': linking,
                'feedback': f'Your pronunciation score is {score}. Keep practicing!'
            }
        })
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

